<script setup>
import {getMethodType} from './common.js'
import {cloneDeep} from "lodash-es";
import SettingPermissionAPI from "@/api/setting/permission.js";
import DevApi from "@/api/dev/index.js";
import {objMerge} from "@/utils/tools.js";

defineProps({
  cascaderData: {
    type: Array,
  }
})

const emits = defineEmits(["close"]);
const priId = ref(0)
const open = (id) => {
  getAllPermissions()
  getPermissionKeys()
  if (id) {
    dialog.title = '编辑'
    priId.value = id
    SettingPermissionAPI.getFormData(id).then(res => {
      subPermissions.value = res.permissions
      objMerge(formData, res)
    })

  } else {
    dialog.title = '新增'
    priId.value = 0
  }
  dialog.visible = true;
}
defineExpose({open});

const dialog = reactive({
  visible: false,
  title: "新增",
});

const formRef = ref();
let formData = reactive({
  pid: 0,
  name: "",
  sort: 0,
  permissions: [],
});

const rules = reactive({
  name: [{required: true, message: "不能为空", trigger: "blur"}],
});


const __DialogClose = () => {
  dialog.visible = false;
  formRef.value.resetFields();
  formRef.value.clearValidate();
  permissionTreeData.value = []
  formData.permissions = []
  subPermissions.value = []
  emits("close");
};

const permissionTreeData = ref([])

const _submit = (formEl) => {
  if (!formEl) return
  console.log(formData)
  const data = cloneDeep(formData)
  formEl.validate((valid, fields) => {
    if (valid) {
      if (Array.isArray(data.pid)) {
        data.pid = data.pid[data.pid.length - 1];
      } else if (!data.pid) {
        data.pid = 0
      }
      data.permissions = allPermissions.value.filter(v => data.permissions.includes(v.slug))
      if (priId.value > 0) {
        SettingPermissionAPI.update(priId.value, data).then(res => {
          __DialogClose()
        })
      } else {
        SettingPermissionAPI.add(data).then(res => {
          __DialogClose()
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const allPermissions = ref([])
const getAllPermissions = () => {
  DevApi.getPermission().then(res => {
    allPermissions.value = res
  })
}
const permissionKeys = ref([])
const getPermissionKeys = () => {
  SettingPermissionAPI.getAllKeys().then(res => {
    permissionKeys.value = res
  })
}
const subPermissions = ref([])
const selectPermissions = computed(() => {
  return allPermissions.value.filter(v => subPermissions.value.includes(v.slug)||!permissionKeys.value.includes(v.slug))
})

</script>

<template>
  <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      append-to-body
      destroy-on-close
      width="30vw"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="__DialogClose"
      draggable
  >
    <el-form ref="formRef" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="上一级" prop="pid">
        <el-cascader
            ref="cascaderRef"
            v-model="formData.pid"
            :options="cascaderData"
            :props="{ value: 'id', label: 'name', checkStrictly: true }"
            clearable
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" maxlength="20" placeholder="名称"/>
      </el-form-item>
      <el-form-item label="权限" prop="permissions">
        <el-select v-model="formData.permissions" multiple>
          <el-option
              v-for="item in selectPermissions"
              :key="item.slug"
              :value="item.slug"
              :label="item.name"
          >
            <span style="float: left">{{ item.name }}</span>
            <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">
              {{ item.uri }}
              <el-tag :type="getMethodType(item.method).type" effect="dark">
                {{ item.method }}
              </el-tag>
            </span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="formData.sort" type="number" class="widthPx-150" placeholder="排序"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="__DialogClose">取 消</el-button>
        <el-button type="primary" @click="_submit(formRef)">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>

</style>
